from PyQt5.QtWidgets import QApplication,  QWidget
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSignal
from PyQt5.Qt import *
from PyQt5.Qt import QThread
from PyQt5 import uic
from threading import Thread

from camera_ import Camera_Thread
from server_ import Server_Tcp

import time
import sys, os
import json

class Window(QWidget):

    gui_signal = pyqtSignal(str)
    server_signal = pyqtSignal(str)

    def __init__(self):
        super().__init__()
        self.setup_ui()
        self.msg_logger=list()
        self.robot_flag = 0
    
    def setup_ui(self,):
        self.ui = uic.loadUi("mainwindow.ui")
        self.textBrowser_log = self.ui.textBrowser_log
        self.label_camera = self.ui.label_camera
        self.initUI()

    def initUI(self):
        self.ui.pushButton_autowork.clicked.connect(self.btn_autowork)
        self.ui.pushButton_handwork.clicked.connect(self.btn_handwork)
        self.ui.pushButton__robotHome.clicked.connect(self.btn_robotHome)
        self.ui.pushButton_robotStop.clicked.connect(self.btn_robotStop)
        self.ui.pushButton_min.clicked.connect(self.btn_min)
        self.ui.pushButton_close.clicked.connect(self.btn_close)

        self.gui_signal.connect(self.gui_signal_dispatch)
        self.server_signal.connect(self.server_signal_dispatch)

        self.ui.label_title.setStyleSheet("background-color:rgb(19, 13, 81);\n""image:url(./IOA8.png);")
        self.ui.pushButton_min.setStyleSheet("background-color:rgb(19, 13, 81);\n""image:url(./min.png);")
        self.ui.pushButton_close.setStyleSheet("background-color:rgb(19, 13, 81);\n""image:url(./close.png);")
        
        # 建立camera线程
        self.camera = Camera_Thread(self.label_camera,self.gui_signal)   
        self.camera.start()
        #### 建立robot线程
        self.server = Server_Tcp(self.server_signal)
        self.server.start()
        self.robot = self.server.robot

    def btn_autowork(self):
        #### 加入一系列机器人动作，IO控制等操作
        self.log("自动模式")

    def btn_handwork(self):
        self.log("手动模式")
    
    def btn_robotHome(self):
        self.server.robot_action = 1
        self.log("机器人复位")

    def btn_robotStop(self):
        self.log("暂停机器人")

    def btn_min(self):
        self.ui.showMinimized()
        print()

    def btn_close(self):
        self.ui.close()
        print()

    def gui_signal_dispatch(self,msg):
        msg = json.loads(msg)
        source = int(msg.get("source"))   # 判断来自哪里的信号
        match source:
            case 0 :
                name = msg.get("name")
                self.log(f"没有检测到{name}")
            
            case 1 :
                name = msg.get("name")            
                self.log(f"正在抓取{name}，请等待！")
            
            case 2:
                self.log(f"没有检测到摄像头！")
            
            case 3:
                self.log("自动运行完毕！")

            case 4:
                self.log("请等待机器人就绪！")

            case 5:
                self.log("请等待机器人移动到拍照位置，重新发布指令！")            

    #### 判断来自哪里的信号
    def server_signal_dispatch(self,msg):
        msg = json.loads(msg)
        source = int(msg.get("source"))   
        
        if source == 1:
            self.log(f"机器人离线，锁定状态")

        elif source == 2:
            self.log(f"机器人空闲状态")

        elif source == 3:
            self.log(f"机器人工作中")
        
        elif source == 4:
            self.log(f"机器人回零中")

    #### 打印日志
    def log(self,msg):
        try:
            msg =time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))+":  "+msg
            self.msg_logger.append(msg)
            self.textBrowser_log.setText("<br>".join(self.msg_logger))
            self.textBrowser_log.moveCursor(self.textBrowser_log.textCursor().End)
            self.textBrowser_log.repaint()  # 更新内容，如果不更新可能没有显示新内容
        except Exception as e:
            print(e)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = Window()
    mainWindow.ui.show()
    sys.exit(app.exec_())
